package com.yanqu.road.server.manger.config;

import com.yanqu.road.entity.config.npc.NpcTalkInfo;
import com.yanqu.road.entity.config.npc.NpcTradeInfo;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.npc.UserNpcGangfen;
import com.yanqu.road.entity.npc.UserNpcTalk;
import com.yanqu.road.entity.npc.UserNpcTrade;
import com.yanqu.road.logic.bussiness.config.NpcConfigBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.activity.eggs.EggsActivityConfig;
import com.yanqu.road.server.manger.activity.eggs.EggsActivityMgr;
import com.yanqu.road.server.manger.system.SystemSwitchMgr;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class NpcConfigMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(NpcConfigMgr.class.getName());

    private static Map<Integer, NpcTalkInfo> npcTalkEventMap;      //npc对话事件

    private static Map<Integer, NpcTradeInfo> npcTradeEventMap;    //npc贸易事件

    private static Map<Integer, NpcTradeInfo> npcGangfenEventMap;    //港分彩蛋事件

    private static Map<Integer,Integer> talkWeightMap = new ConcurrentHashMap<>(); //npc对话权限

    private static Map<Integer,Integer> tradeWeightMap = new ConcurrentHashMap<>(); //npc贸易权限

    private static Map<Integer,Integer> gangfenWeightMap = new ConcurrentHashMap<>(); //港分彩蛋权限

    private static RandomHelper random = new RandomHelper();

    public static NpcTalkInfo getNpcTalkInfo(int eventId){
        return npcTalkEventMap.get(eventId);
    }

    public static NpcTradeInfo getNpcTradeInfo(int eventId){
        return npcTradeEventMap.get(eventId);
    }

    public static int getRandomEvent(Map<Integer,Integer> randomMap){
        int res = 0;
        int totalWeight = 0;
        for (int weight : randomMap.values()){
            totalWeight += weight;
        }
        int randomNum = random.next(0, totalWeight);
        for(int key : randomMap.keySet()){
            if(randomNum < randomMap.get(key)){
                res = key;
                break;
            }
            randomNum = randomNum - randomMap.get(key);
        }

        return res;
    }

    private static NpcTalkInfo getRandomNpcTalkInfo(){
        Map<Integer, Integer> tempTalkMap = new ConcurrentHashMap<>();
        for (Map.Entry<Integer, Integer> entry : talkWeightMap.entrySet()) {
            NpcTalkInfo npcTalkInfo = npcTalkEventMap.get(entry.getKey());
            if (npcTalkInfo == null || (SystemSwitchMgr.getLockSystemIdList().contains(eSystemId.NpcTalkEventChoose.getValue())
                    && npcTalkInfo.getType() == 10)) {
                continue;
            }
            tempTalkMap.put(entry.getKey(), entry.getValue());
        }
        return npcTalkEventMap.get(getRandomEvent(tempTalkMap));
    }

    private static NpcTradeInfo getRandomNpcTradeInfo(){
        return npcTradeEventMap.get(getRandomEvent(tradeWeightMap));
    }

    private static NpcTradeInfo getRandomNpcGangfenInfo(){
        return npcGangfenEventMap.get(getRandomEvent(gangfenWeightMap));
    }

    public static NpcTalkInfo getNpcTalkInfoByNo(int no){
        List<Integer> defaultEventList = StringUtils.stringToIntegerList(GameConfig.NPC_TALK_EVENT_DEFAULT,";");
        if(defaultEventList.size() < no){
            return getRandomNpcTalkInfo();
        }
        return getNpcTalkInfo(defaultEventList.get(no-1));
    }

    public static NpcTradeInfo getNpcTradeInfoByNo(int no){
        List<Integer> defaultEventList = StringUtils.stringToIntegerList(GameConfig.NPC_TRADE_EVENT_DEFAULT,";");
        if(defaultEventList.size() < no){
            return getRandomNpcTradeInfo();
        }

        return getNpcTradeInfo(defaultEventList.get(no-1));
    }

    public static NpcTradeInfo getNpcGangfenInfoByNo(){
        return getRandomNpcGangfenInfo();
    }

    //判断是不是固定的前几个商贸事件
    public static boolean isDefaultTradeInfo(int no){
        List<Integer> defaultEventList = StringUtils.stringToIntegerList(GameConfig.NPC_TRADE_EVENT_DEFAULT,";");
        if(no <= defaultEventList.size()){
            return true;
        }
        return false;
    }

    //判断npc对话时间是不是到了刷新时间了
    public static boolean isNpcTalkRefreshTime(UserNpcTalk userNpcTalk){
        if(userNpcTalk == null){
            return false;
        }
        List<Long> refreshTimeList = StringUtils.stringToLongList(GameConfig.NPC_TALK_EVENT_REFRESH_TIME,";");
        long todayZeroTime = DateHelper.getTodayZeroTimeStamp();
        for(long second : refreshTimeList){
            long refreshTime = todayZeroTime + second*1000;
            if(System.currentTimeMillis() >= refreshTime && userNpcTalk.getRefreshTime() <= refreshTime){
                if(userNpcTalk.getStatus() == 1){
                    return true;
                }else{
                    if(userNpcTalk.getEventId() > 0) {//如果有事件，但是找不到配置，重新刷一次
                        NpcTalkInfo npcTalkInfo = null;
                        if (EggsActivityMgr.isActivityInShowTime()) {
                            EggsActivityConfig eggsActivityConfig = EggsActivityMgr.getEggsActivityConfig();
                            if (null != eggsActivityConfig) {
                                npcTalkInfo = eggsActivityConfig.getNpcTalkInfo(userNpcTalk.getEventId());
                            }
                        }
                        if (null == npcTalkInfo) {
                            npcTalkInfo = getNpcTalkInfo(userNpcTalk.getEventId());
                        }
                        if (null == npcTalkInfo) {
                            return true;
                        }
                    }
                    userNpcTalk.setRefreshTime(System.currentTimeMillis());
                }
            }
        }
        return false;
    }

    public static boolean isNpcTradeRefreshTime(UserNpcTrade userNpcTrade){
        if(userNpcTrade == null){
            return false;
        }
        long refreshTime = GameConfig.NPC_TRADE_EVENT_REFRESH_TIME;
        if(userNpcTrade.getStatus() == 0 && System.currentTimeMillis() - userNpcTrade.getRefreshTime() >= refreshTime * 1000){
            return true;
        }
        return false;
    }

    public static boolean isNpcGangFenRefreshTime(UserNpcGangfen userNpcGangfen){
        if(userNpcGangfen == null){
            return false;
        }
        long refreshTime = GameConfig.HONGKONG_WIND_EVENT_REFRESH_TIME;
        if(System.currentTimeMillis() - userNpcGangfen.getRefreshTime() >= refreshTime * 1000){
            return true;
        }
        return false;
    }


    @Override
    public boolean reloadConfig() {
        npcTalkEventMap = NpcConfigBussiness.getNpcTalkInfoMap();
        npcTradeEventMap = NpcConfigBussiness.getNpcTradeInfoMap();
        npcGangfenEventMap = NpcConfigBussiness.getGanefenInfoMap();

        for(NpcTalkInfo npcTalkInfo : npcTalkEventMap.values()){
            talkWeightMap.put(npcTalkInfo.getEventId(),npcTalkInfo.getWeight());
        }

        for(NpcTradeInfo npcTradeInfo : npcTradeEventMap.values()){
            tradeWeightMap.put(npcTradeInfo.getEventId(),npcTradeInfo.getWeight());
        }

        for(NpcTradeInfo npcTradeInfo : npcGangfenEventMap.values()){
            gangfenWeightMap.put(npcTradeInfo.getEventId(),npcTradeInfo.getWeight());
        }
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static Map<Integer, NpcTalkInfo> getNpcTalkEventMap() {
        return npcTalkEventMap;
    }
}
